//
//  PersonalInformationViewController.swift
//  IDF
//
//  Created by 陈徐挺 on 27/03/2018.
//  Copyright © 2018 Jesse.chen. All rights reserved.
//

import UIKit
import Dollar
import DatePickerDialog

class PersonalInformationViewController: BaseViewController {

    let formData = [
        ["title": "<span style=\"font-family: PingFang SC; font-size:14px;color: #888888\"><span style=\"color: #D0021B\">*</span>Full name</span>"],
        ["title": "<span style=\"font-family: PingFang SC; font-size:14px;color: #888888\"><span style=\"color: #D0021B\">*</span>ID Card number</span>"],
        ["title": "<span style=\"font-family: PingFang SC; font-size:14px;color: #888888\"><span style=\"color: #D0021B\">*</span>Birthday</span>"],
        ["title": "<span style=\"font-family: PingFang SC; font-size:14px;color: #888888\"><span style=\"color: #D0021B\">*</span>Gender</span>"],
        ["title": "<span style=\"font-family: PingFang SC; font-size:14px;color: #888888\"><span style=\"color: #D0021B\">*</span>Residential province</span>"],
        ["title": "<span style=\"font-family: PingFang SC; font-size:14px;color: #888888\"><span style=\"color: #D0021B\">*</span>address</span>"],
//        ["title": "<span style=\"font-family: PingFang SC; font-size:14px;color: #888888\"><span style=\"color: #D0021B\"></span>Biological mother’s name</span>"],
//        ["title": "<span style=\"font-family: PingFang SC; font-size:14px;color: #888888\"><span style=\"color: #D0021B\"></span>Education</span>"],
//        ["title": "<span style=\"font-family: PingFang SC; font-size:14px;color: #888888\"><span style=\"color: #D0021B\"></span>Martial status</span>"],
//        ["title": "<span style=\"font-family: PingFang SC; font-size:14px;color: #888888\"><span style=\"color: #D0021B\"></span>Number of children</span>"],
//        ["title": "<span style=\"font-family: PingFang SC; font-size:14px;color: #888888\"><span style=\"color: #D0021B\"></span>Occupancy duration</span>"],
//        ["title": "<span style=\"font-family: PingFang SC; font-size:14px;color: #888888\"><span style=\"color: #D0021B\"></span>facebook/instagram</span>"],
    ]
//    let formData = [
//        ["title": "Full name"],
//        ["title": "ID Card number"],
//        ["title": "Biological mother’s name"],
//        ["title": "Gender"],
//        ["title": "Education"],
//        ["title": "Martial status"],
//        ["title": "Number of children"],
//        ["title": "Residential province"],
//        ["title": "address"],
//        ["title": "Occupancy duration"],
//        ["title": "facebook/instagram"],
//    ]
    var tfArr: [UITextField] = Array(repeating: UITextField(), count: 13)
    var userPersonalInfo: UserPersonalInfo!
    @IBOutlet weak var saveButtonView: FooterButtonView!
    @IBOutlet weak var baseTableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "Personal information"
        baseTableView.register(cellType: InputTableViewCell.self)
        saveButtonView.doneButton.setBlockFor(.touchUpInside) { [weak self] (button) in
            EZAlertController.alert("Save information", message: "Whether to save the modified information？", buttons: ["Give up", "Save"], tapBlock: { (_, index) in
                if index == 1 {
                    let _ = self?.userPersonalInfo.save().then { _ -> Void in
                        nowNavgationController.popViewController(animated: true)
                    }

                }
            })
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }



    func saveData(_ tf: UITextField) {
        switch tf.tag {
        case 0:
            userPersonalInfo.fullName = tf.text!
        case 1:
            userPersonalInfo.idCard = tf.text!
        case 2:
            userPersonalInfo.birthday = tf.text!
        case 3:
            if let selection = getSelection(key: "sex", selectText: tf.text!) {
                userPersonalInfo.gender = selection.selectValue
            }
        case 4:
            userPersonalInfo.residentialProvince = tf.text!
        case 5:
            userPersonalInfo.address = tf.text!
        case 6:
            userPersonalInfo.motherName = tf.text!
        case 7:
            if let selection = getSelection(key: "education", selectText: tf.text!) {
                userPersonalInfo.education = selection.selectValue
            }
        case 8:
            if let selection = getSelection(key: "marital", selectText: tf.text!) {
                userPersonalInfo.maritalStatus = selection.selectValue
            }
        case 9:
            if let selection = getSelection(key: "children", selectText: tf.text!) {
                userPersonalInfo.numberOfChildren = selection.selectValue
            }
        case 10:
            if let selection = getSelection(key: "occupancyduration", selectText: tf.text!) {
                userPersonalInfo.occupancyDuration = selection.selectValue
            }
        case 11:
            userPersonalInfo.socialAccounts = tf.text!
        default:
            break
        }


    }

    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */

}
extension PersonalInformationViewController: UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return formData.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: InputTableViewCell = tableView.dequeueReusableCell(for: indexPath)
        var htmlText = formData[indexPath.row]["title"]
        cell.fieldLabel.attributedText = htmlText?.html2AttributedString
        cell.fieldTF.text = ""
        cell.fieldTF.delegate = self
        cell.fieldTF.tag = indexPath.row
        cell.accessoryType = .none
        switch indexPath.row {
        case 0:
            cell.fieldTF.text = userPersonalInfo.fullName
        case 1:
            cell.fieldTF.text = userPersonalInfo.idCard
        case 2:
            cell.fieldTF.isEnabled = false
            cell.fieldTF.text = userPersonalInfo.birthday
        case 3:
            cell.fieldTF.isEnabled = false
            cell.selection = getSelection(key: "sex", selectValue: userPersonalInfo.gender)
            if let s = cell.selection {
                cell.fieldTF.text = s.selectText
            }
            cell.accessoryType = .disclosureIndicator
        case 4:
            cell.fieldTF.text = userPersonalInfo.residentialProvince
//            cell.fieldTF.isEnabled = false
//            cell.selection = getSelection(key: "province", selectValue: userPersonalInfo.residentialProvince)
//            if let s = cell.selection {
//                cell.fieldTF.text = s.selectText
//            }
//            cell.accessoryType = .disclosureIndicator
        case 5:
            cell.fieldTF.text = userPersonalInfo.address
        case 6:
            cell.fieldTF.text = userPersonalInfo.motherName
        case 7:
            cell.fieldTF.isEnabled = false
            cell.selection = getSelection(key: "education", selectValue: userPersonalInfo.education)
            if let s = cell.selection {
                cell.fieldTF.text = s.selectText
            }
            cell.accessoryType = .disclosureIndicator
        case 8:
            cell.fieldTF.isEnabled = false
            cell.selection = getSelection(key: "marital", selectValue: userPersonalInfo.maritalStatus)
            if let s = cell.selection {
                cell.fieldTF.text = s.selectText
            }
            cell.accessoryType = .disclosureIndicator
        case 9:
            cell.fieldTF.isEnabled = false
            cell.selection = getSelection(key: "children", selectValue: userPersonalInfo.numberOfChildren)
            if let s = cell.selection {
                cell.fieldTF.text = s.selectText
            }
            cell.accessoryType = .disclosureIndicator
        case 10:
            cell.fieldTF.isEnabled = false
            cell.selection = getSelection(key: "occupancyduration", selectValue: userPersonalInfo.occupancyDuration)
            if let s = cell.selection {
                cell.fieldTF.text = s.selectText
            }
            cell.accessoryType = .disclosureIndicator
        case 11:
            cell.fieldTF.text = userPersonalInfo.socialAccounts
        default:
            break
        }
        tfArr[indexPath.row] = cell.fieldTF
        return cell
    }



    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let cell = tableView.cellForRow(at: indexPath) as! InputTableViewCell
        cell.fieldTF.isEnabled = true
        cell.fieldTF.becomeFirstResponder()
        func setOptions(_ string: String) {
            let arr = appSelection.filter { (selection) -> Bool in
                return selection.selectType == string
            }
            let opt = OptionsView(frame: appWindow.bounds)
            opt.setWithOptions(arr)
            appWindow.addSubview(opt)
            opt.show()
            opt.clickCallback = { [weak self] section -> Void in
                cell.selection = section
                cell.fieldTF.text = section.selectText
                self?.saveData(cell.fieldTF)
            }
        }
        switch indexPath.row {
        case 2:
            cell.fieldTF.resignFirstResponder()
            cell.fieldTF.isEnabled = false
            DatePickerDialog().show("Select Birthday", doneButtonTitle: "Done", cancelButtonTitle: "Cancel", datePickerMode: .date) {[weak self]
                (date) -> Void in
                if let dt = date {
                    let formatter = DateFormatter()
                    formatter.dateFormat = "yyyy-MM-DD"
                    cell.fieldTF.text = formatter.string(from: dt)
                    self?.saveData(cell.fieldTF)
                }
            }
        case 3:
            cell.fieldTF.resignFirstResponder()
            cell.fieldTF.isEnabled = false
            setOptions("sex")
        case 7:
            cell.fieldTF.resignFirstResponder()
            cell.fieldTF.isEnabled = false
            setOptions("education")
        case 8:
            cell.fieldTF.resignFirstResponder()
            cell.fieldTF.isEnabled = false
            setOptions("marital")
        case 9:
            cell.fieldTF.resignFirstResponder()
            cell.fieldTF.isEnabled = false
            setOptions("children")
//        case 4:
//            cell.fieldTF.resignFirstResponder()
//            cell.fieldTF.isEnabled = false
//            setOptions("province")
        case 10:
            cell.fieldTF.resignFirstResponder()
            cell.fieldTF.isEnabled = false
            setOptions("occupancyduration")
        default:
            break
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 66
    }
    func textFieldDidBeginEditing(_ textField: UITextField) {
        saveData(textField)
    }
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        saveData(textField)
        return true
    }
}


